import { message, open } from '@tauri-apps/api/dialog';
import { desktopDir } from '@tauri-apps/api/path';
import { getAllProDirs } from '@/services/fs';
import windowManager from '@/utils/WindowManager';
import { WinEnums } from '@/utils/enums';
import { queryProjects } from '@/services';

export default function useCreateImportWindow() {
  const chooseImportDir = async () => {
    const selected = (await open({
      directory: true,
      defaultPath: await desktopDir(),
    })) as string;
    return selected;
  };

  const createImportWindow = async () => {
    if (windowManager.isExsitWin(WinEnums.IMPORT_WIN)) {
      await message('导入窗口已存在，请先完成当前导入工作。', {
        title: '提示',
        type: 'error',
      });
      return;
    }
    // # 选择目录
    const dirPath = await chooseImportDir();
    // # 解析目录中所有项目的信息只解析一层
    const dirList: string[] = (await getAllProDirs(dirPath)) as string[];
    if (!Array.isArray(dirList) || !dirList.length) {
      await message('该目录中没有可用项目', {
        title: '提示',
        type: 'error',
      });
      return;
    }

    const proList = (await queryProjects()) as {
      list: ProjectItem[];
      total: number;
    };

    const nProListMap: Map<string, boolean> = (
      (proList || {}).list || []
    ).reduce((p, c) => {
      if (c.workSpace) {
        p.set(c.workSpace, true);
      }
      return p;
    }, new Map<string, boolean>());

    const workSpaceList: string[] = [];
    dirList.forEach((workSpace: string) => {
      if (nProListMap.has(workSpace)) return;
      workSpaceList.push(workSpace);
    });

    if (!Array.isArray(workSpaceList) || !workSpaceList.length) {
      await message('选中的目录中的项目都已导入，请勿重复导入！', {
        title: '提示',
        type: 'error',
      });
      return;
    }

    // # 创建新窗口，并发送数据
    windowManager.createWin(
      {
        label: WinEnums.IMPORT_WIN,
        title: '批量导入',
        url: '/#/batch-import',
        width: 800,
        height: 600,
      },
      {
        onCreated: () => {
          localStorage.setItem(
            'init-import-win',
            JSON.stringify(workSpaceList),
          );
        },
      },
    );
  };
  return { createImportWindow };
}
